<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="项目编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['projectCode']"
                :trigger-change="true"
                dictCode="project_info,name,code"
                placeholder="请选择项目编码"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <!-- 添加的多选 -->
            <a-form-item label="处理人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-multi-select-tag
                type="select"
                v-decorator="['handlerUserId']"
                :options="dictOptions"
                placeholder="请选择处理人">
              </j-multi-select-tag>
            </a-form-item>
            <!-- 添加的end -->
          </a-col>
          <a-col :span="24">
            <a-form-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['title']" placeholder="请输入标题"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="内容" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-decorator="['content']" rows="4" placeholder="请输入内容"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="优先级" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="radio"
                v-decorator="['fristLevel', validatorRules.fristLevel]"
                :trigger-change="true"
                dictCode="frist_level"
                placeholder="请选择优先级"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="附件字段" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload v-decorator="['fileUrl']" :trigger-change="true"></j-upload>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
      </a-table>
    </div>
  </a-spin>
</template>

<script>
  import { getAction, httpAction } from '@/api/manage'
  import { getOrderList, getUserList } from '@/api/order'
  import pick from 'lodash.pick'

  export default {
    name: 'WorkOrderForm',
    components: {},
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: () => {
        },
        required: false,
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false,
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
    },
    data() {
      return {
        form: this.$form.createForm(this),
        model: {},
        dictOptions: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {},
        url: {
          add: '/order/workOrder/add',
          edit: '/order/workOrder/edit',
          queryById: '/order/workOrder/queryById',
        },
        userList: [],
        itemList: {},
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '处理人',
            width: 200,
            align: 'center',
            dataIndex: 'createBy',
          },
          {
            title: '处理意见',
            align: 'center',
            dataIndex: 'content',
          },
          {
            title: '处理时间',
            align: 'center',
            width: 100,
            dataIndex: 'createTime',
          },
        ],
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        loading: false,
        /* table选中keys*/
        selectedRowKeys: [],
        /* table选中records*/
        selectionRows: [],
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      },
    },

    async created() {
      //如果是流程中表单，则需要加载流程表单data

      this.showFlowData()

    },
    methods: {
      // 获取 处理人列表
      async getUserList() {
        const { code, message, result } = await getUserList({ roleCode: 'developer' })
        if (code != 200) {
          return this.$message.error(message)
        }
        result.map((val) => {
          this.dictOptions.push({ label: val.realname, value: val.id })
        })
        console.log("数据",this.dictOptions)
      },
      add() {
        this.edit({})
      },
      async edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.itemList = record
        if (record.id) {
          this.getOrderList()
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.model,
              'title',
              'content',
              'fileUrl',
              'projectCode',
              'handlerUserId',
              'applyUsername',
              'applyType',
              'fristLevel'
            )
          )
        })
        await this.getUserList()

      },
      async getOrderList() {
        const params = {
          orderId: this.itemList.id,
          pageNo: this.ipagination.current,
          pageSize: this.ipagination.pageSize,
        }
        const { code, message, result } = await getOrderList(params)
        if (code != 200) {
          return this.$message.error(message)
        }
        this.dataSource = result.records
        this.ipagination.total = result.total
      },
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        // if (Object.keys(sorter).length > 0) {
        //   this.isorter.column = sorter.field;
        //   this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        // }
        this.ipagination = pagination
        this.getOrderList()
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      //渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId }
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result)
            }
          })
        }
      },
      submitForm() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            httpAction(httpurl, formData, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      },
      popupCallback(row) {
        this.form.setFieldsValue(
          pick(row, 'title', 'content', 'fileUrl', 'projectCode', 'handlerUserId', 'applyUsername', 'applyType')
        )
      },
    },
  }
</script>